/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.ove.clientserver;

/**
 *
 * @author Mr.Sam
 */
import fr.ove.utils.Connection;
import fr.ove.utils.ConnectionHandler;
import fr.ove.openmath.mathematica.ResponseReader;
import java.io.IOException;

/**
* A ConnectionHandler implementation.<BR>
* This connection handler is used with a server which connects to an another one.
* The objects sent from a connected client are sent to the server the server whose
* instance deals the conections is connected.
*/
public class EchoConnectionHandler implements ConnectionHandler {
    Connection connection;
    /**
    * The constructor.
    */
    public EchoConnectionHandler() {
    }
    
    // #################################
    // ### Interfaces Implementation ###
    // #################################    

    // ConnectionHandler interface

    /**
    * Handles the specified connection.
    * @param connection the connection to handle.
    */
    public void handleConnection(Connection connection) {
        new Echoer(connection);
    }
    
    /**
    *
    */
    private class Echoer implements Runnable {
        private Connection connection;
        private ResponseReader reader = new ResponseReader();
        
        public Echoer(Connection connection) {
            this.connection = connection;
            new Thread(this).start();
        }
        // Runnable interface

        /**
        *
        */
        public void run() {
            String object = null;
            
            while (true) {
                try {Thread.sleep(100);} catch (Exception e) {e.printStackTrace();}
                if (connection != null) {
                    // Read the object sent by the client.
                    object = reader.read(connection.getInputStream());
                    
                    //try {Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}
                    
                    // if we got it, send it to the server
                    if (object != null) {
                        try {
                            connection.getOutputStream().write(object.getBytes());
                        }
                        catch (IOException ioe) {
                            System.out.println("Failed to send back the object");
                            ioe.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
